Component({
  data: {
    tabList: [
      {
        pagePath: 'pages/index/index',
        text: '首页',
        iconName: 'home',
        selected: false
      },
      {
        pagePath: 'pages/category/category',
        text: '分类',
        iconName: 'category',
        selected: false
      },
      {
        pagePath: 'pages/cart/cart',
        text: '购物车',
        iconName: 'cart',
        selected: false
      },
      {
        pagePath: 'pages/profile/profile',
        text: '我的',
        iconName: 'profile',
        selected: false
      }
    ]
  },

  attached() {
    this.updateTabBarState();
  },

  methods: {
    switchTab(e) {
      const index = e.currentTarget.dataset.index;
      const tabItem = this.data.tabList[index];
      
      // 更新选中状态
      const newTabList = this.data.tabList.map((item, i) => ({
        ...item,
        selected: i === index
      }));
      
      this.setData({
        tabList: newTabList
      });

      // 跳转页面
      wx.switchTab({
        url: `/${tabItem.pagePath}`
      });
    },

    updateTabBarState() {
      const pages = getCurrentPages();
      const currentPage = pages[pages.length - 1];
      const currentRoute = currentPage.route;

      const newTabList = this.data.tabList.map(item => ({
        ...item,
        selected: item.pagePath === currentRoute
      }));

      this.setData({
        tabList: newTabList
      });
    }
  }
});